package com.fjwt.gz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.dto.AwardCouponDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.FansMchVO;
import com.fjwt.gz.service.mapper.FansMchMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员绑定商户关系表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class FansMchService extends ServiceImpl<FansMchMapper, FansMchEntity> {
    @Autowired
    FansMchMapper fansMchMapper;
    @Autowired
    private AwardCouponService awardCouponService;
    @Autowired
    protected AwardMchService awardMchService;
    @Autowired
    protected ActivityService activityService;
    @Autowired
    protected ActivityAwardService activityAwardService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private MchChannelService mchChannelService;
    @Autowired
    private ActivityAppService activityAppService;


    //查询列表
    public List<FansMchVO> getSaveFile(Long fansId, String locationAgentNo) {
        return fansMchMapper.getSaveFile(fansId, locationAgentNo);
    }

    //创建活动卡券
    @Transactional
    public ApiRes add(AwardCouponEntity couponAwardEntity, Long userId, Long fansId, String appId) throws Exception {

        LambdaQueryWrapper<MchChannelEntity> queryWrapper = MchChannelEntity.gw();
        queryWrapper.eq(MchChannelEntity::getMchNo, couponAwardEntity.getMchNo());
        queryWrapper.eq(MchChannelEntity::getState, 1);
        List<MchChannelEntity> mchChannelEntity = mchChannelService.list(queryWrapper);
        if (mchChannelEntity.size() == 0){
            throw new ServiceException("商户查询为空");
        }
        if (mchChannelEntity.size() > 1){
            throw new ServiceException("商户对应多个通道，请联系管理员");
        }
        if (mchChannelEntity.size() == 1){
            boolean gtpay = mchChannelEntity.get(0).getIfCode().equals("gtpay");
            if (!gtpay){
                throw new ServiceException("无效商户号");
            }
        }

        MchInfoEntity mchInfo = mchInfoService.getBaseMapper().selectById(couponAwardEntity.getMchNo());
        AwardCouponEntity cope = couponAwardEntity;
//        couponAwardEntity.setPayConfig(jsonObject.toJSONString());
//        jsonObject.put("appid", "wx313cfd5a1d78e709");
//        couponAwardEntity.setApiJson(couponAwardEntity.toString());
//        couponAwardEntity.setApiJson(String.valueOf(couponAwardEntity));
        couponAwardEntity.setState(2);
        couponAwardEntity.setAgentNo(mchInfo.getAgentNo());
        couponAwardEntity.setEveryoneMaxNum(couponAwardEntity.getEveryoneMaxNum());
        awardCouponService.save(couponAwardEntity);

        AwardMchEntity awardMchEntity = new AwardMchEntity();
        awardMchEntity.setMchNo(couponAwardEntity.getMchNo());
        awardMchEntity.setAwardId(couponAwardEntity.getCouponId());
        awardMchEntity.setAwardType(0);
        awardMchEntity.setNumVerify(0);
        awardMchEntity.setCreatedAt(new Date());
        awardMchEntity.setUpdatedAt(new Date());
        awardMchService.save(awardMchEntity);

        ActivityEntity activityEntity = new ActivityEntity();
        activityEntity.setActivityTemplateNo("ACTE026");
        activityEntity.setActivityName(couponAwardEntity.getCouponName());
        activityEntity.setStartTime(couponAwardEntity.getStartTime());
        activityEntity.setEndTime(couponAwardEntity.getEndTime());
        activityEntity.setRemark("商家配券");
        activityEntity.setCreatedUid(userId);
        //商户归属网点
        activityEntity.setAgentNo("22011060");
        activityEntity.setAgentNo1("22000030");
        activityEntity.setAgentNo2("22011060");
        activityEntity.setAgentNo3("0");
        activityEntity.setAgentNo4("0");
        // 生成 ACNO 加时间戳的格式
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String activityNo = "ACNO" + now.format(formatter);
        activityEntity.setActivityNo(activityNo);
        activityEntity.setCreatedAt(new Date());
        activityEntity.setUpdatedAt(new Date());
        activityEntity.setState(1);
        activityEntity.setPayAuthId(9L);
        activityEntity.setRemark(JSONObject.toJSONString(cope));
        activityService.save(activityEntity);

        ActivityAwardEntity activityAwardEntity = new ActivityAwardEntity();
        activityAwardEntity.setActivityId(activityEntity.getActivityId());
        activityAwardEntity.setAwardId(couponAwardEntity.getCouponId());
        activityAwardEntity.setAwardName(couponAwardEntity.getCouponName());
        activityAwardEntity.setAwardType(0);
        activityAwardEntity.setAwardLevel(0);
        activityAwardEntity.setAwardProbability(0);
        activityAwardEntity.setCreatedAt(new Date());
        activityAwardService.save(activityAwardEntity);

        ActivitySettingEntity activityLimitUserEntity = new ActivitySettingEntity();
        activityLimitUserEntity.setActivityId(activityEntity.getActivityId());
        activityLimitUserEntity.setOnlyOneTimes(couponAwardEntity.getEveryoneMaxNum());
        activityLimitUserEntity.setPeriodType(couponAwardEntity.getPeriodType());

        activityLimitUserEntity.setPeriodTimes(couponAwardEntity.getPeriodTimes());
        activityLimitUserEntity.setSpecialType(0);
        activityLimitUserEntity.setTimeType(0);
        activityLimitUserEntity.setThresholdType(0);
        activityLimitUserEntity.setCreatedAt(new Date());
        activityLimitUserEntity.setIsFollowOfficial(0);
        activitySettingService.save(activityLimitUserEntity);

        ActivityAppEntity activityAppEntity = new ActivityAppEntity();
        activityAppEntity.setActivityId(activityEntity.getActivityId());
        activityAppEntity.setAppId(appId);
        activityAppEntity.setType(1);
        activityAppService.save(activityAppEntity);

        AwardSettingEntity awardSettingEntity = new AwardSettingEntity();
        awardSettingEntity.setAwardId(couponAwardEntity.getCouponId());
        awardSettingEntity.setAwardType(Constants.AWARD.COUPON);
        awardSettingEntity.setEveryoneMaxNum(couponAwardEntity.getPeriodType());
        awardSettingEntity.setPeriodTimes(couponAwardEntity.getPeriodTimes());
        awardSettingEntity.setCreatedAt(new Date());
        awardSettingService.save(awardSettingEntity);

        if (activityEntity.getState() != null && activityEntity.getState() == 1) {
//            activityService.addExamineRecord(activityId, activityDTO.getActivityTemplateNo());
            activityService.mchAddAuditRecords(activityEntity.getActivityId(),fansId);
        }

        return ApiRes.ok();
    }

    //创建活动卡券
    @Transactional
    public ApiRes upCouponInfo( Long activityId,Long fansId,AwardCouponEntity couponAwardEntity) throws Exception {

        AwardCouponEntity pro = couponAwardEntity;

//        CouponAwardEntity couponAward = couponAwardService.getBaseMapper().selectById(awardId);
//        couponAward.setPayConfig(jsonObject.toJSONString());
//        jsonObject.put("appid", "wx313cfd5a1d78e709");
//        couponAward.setApiJson(jsonObject.toJSONString());
//        couponAwardService.save(couponAward);


        AwardCouponEntity couponAward = awardCouponService.getBaseMapper().selectById(couponAwardEntity.getCouponId());
        couponAward.setCouponName(couponAwardEntity.getCouponName());
        couponAward.setPayAmount(couponAwardEntity.getPayAmount());
        couponAward.setCouponNum(couponAwardEntity.getCouponNum());
        couponAward.setEveryoneMaxNum(couponAwardEntity.getEveryoneMaxNum());
        couponAward.setStartTime(couponAwardEntity.getStartTime());
        couponAward.setEndTime(couponAwardEntity.getEndTime());
        couponAward.setCouponPrice(couponAwardEntity.getCouponPrice());
        awardCouponService.updateById(couponAward);


        ActivityEntity activityEntity = activityService.getBaseMapper().selectById(activityId);
        activityEntity.setState(1);
        activityEntity.setStartTime(couponAwardEntity.getStartTime());
        activityEntity.setEndTime(couponAwardEntity.getEndTime());
        String activityJson = activityEntity.getRemark();
        AwardCouponEntity couponAward1 = JSONObject.parseObject(activityJson, AwardCouponEntity.class);
        couponAward1.setCouponName(couponAwardEntity.getCouponName());
        couponAward1.setPayAmount(couponAwardEntity.getPayAmount());
        couponAward1.setCouponNum(couponAwardEntity.getCouponNum());
        couponAward1.setEveryoneMaxNum(couponAwardEntity.getEveryoneMaxNum());
        couponAward1.setStartTime(couponAwardEntity.getStartTime());
        couponAward1.setEndTime(couponAwardEntity.getEndTime());
        couponAward1.setCouponPrice(couponAwardEntity.getCouponPrice());
        activityEntity.setRemark(JSONObject.toJSONString(couponAward1));
        activityService.updateById(activityEntity);


        if (activityEntity.getState() != null && activityEntity.getState() == 1) {
//            activityService.addExamineRecord(activityId, activityDTO.getActivityTemplateNo());
            activityService.mchAddAuditRecords(activityEntity.getActivityId(),fansId);
        }

        return ApiRes.ok();
    }

    /**
     * 每日或卡券查询
     */

    public List<AwardCouponDTO> selectProcess() {
        LambdaQueryWrapper<ActivityEntity> activityWrapper = new LambdaQueryWrapper<>();
        activityWrapper.eq(ActivityEntity::getActivityTemplateNo, "ACTE026");
        List<AwardCouponDTO> couponAwardList = new ArrayList<>();
        List<ActivityEntity> activityList = activityService.list(activityWrapper);
        for (ActivityEntity activityEntity : activityList){
            List<AwardCouponDTO> list = awardCouponService.selectProcessCopy(activityEntity.getActivityId());
            for (AwardCouponDTO couponAward : list){
                couponAward.setNumberSheets(couponAward.getCouponNum()-couponAward.getCouponGet());
                couponAwardList.add(couponAward);
            }
        }
        return couponAwardList;
    }

}
